/*
 * @Author: Eason
 * @Date:   2020-01-16 09:17:05
 * @Last Modified by: Eason
 * @Last Modified time: 2020-12-14 16:44:05
 */
import { router } from 'umi';
import { notification } from 'antd';
import { setLocale } from 'umi-plugin-react/locale';
import { message, utils } from 'suid';
import {
  userLogin,
  bindingSocialAccount,
  getVerifyCode,
  getUserByXsid,
  updatePwd,
  sendVerifyCode,
  findpwd,
  checkExisted,
} from '@/services/user';
import { userInfoOperation, eventBus, constants } from '@/utils';

const { storage } = utils;
const defaultHeadIcon =
  '';

const { LOCALE_USER_LIST_KEY } = constants;
const {
  setCurrentUser,
  setSessionId,
  clearUserInfo,
  setCurrentLocale,
  getCurrentLocale,
  adaptLocale,
  setCurrentPolicy,
} = userInfoOperation;

export default {
  namespace: 'user',

  state: {
    userInfo: null,
    sessionId: null,
    verifyCode: null,
    qrConfig: null,
  },

  subscriptions: {
    eventBusListenter({ dispatch }) {
      eventBus.addListener('redirectLogin', () => {
        dispatch({
          type: 'redirectLogin',
        });
      });
    },
  },

  effects: {
    *processUser({ payload }, { put }) {
      const { userInfo } = payload;
      const { sessionId, locale, authorityPolicy, account, userName } = userInfo || {};
      const userData = storage.localStorage.get(LOCALE_USER_LIST_KEY) || [];
      const localUsers = userData.filter(u => u.account === account);
      if (localUsers.length === 0) {
        userData.unshift({ account, userName });
      }
      storage.localStorage.set(LOCALE_USER_LIST_KEY, userData);
      const portrait = defaultHeadIcon;
      setSessionId(sessionId);
      setCurrentPolicy(authorityPolicy);
      setCurrentLocale(adaptLocale(locale || 'zh_CN'));
      setLocale(adaptLocale(locale || 'zh_CN'));
      // const resultPortrait = yield call(getPortrait);
      // if (resultPortrait.success) {
      //   portrait = resultPortrait.data || defaultHeadIcon;
      // }
      yield put({
        type: 'updateState',
        payload: {
          userInfo: {
            ...userInfo,
            portrait,
          },
          sessionId,
        },
      });
      setCurrentUser({ ...userInfo, portrait });
    },
    *bindingSocialAccount({ payload }, { call }) {
      const result = yield call(bindingSocialAccount, payload);
      const { success, data, message: msg } = result || {};
      if (success) {
        if (data && data.redirectUrl) {
          window.open(data.redirectUrl, '_self');
        }
      } else {
        notification.error({
          message: '请求错误',
          description: msg,
        });
      }
    },
    *getUserByXsid({ payload }, { put, call, take }) {
      const result = yield call(getUserByXsid, payload);
      const { success, data, message: msg } = result || {};
      if (success) {
        yield put({
          type: 'processUser',
          payload: {
            userInfo: data,
          },
        });
        yield take('processUser/@@end');
        router.replace('/');
      } else {
        notification.error({
          message: '请求错误',
          description: msg,
        });
      }

      return result;
    },
    *userLogin({ payload }, { put, take }) {
      const { account, password } = payload;
      const result = {
        success: true,
        error: false,
        message: '处理成功！',
        detail: '',
        data: {
          sessionId: '15FEDC32-7EAD-11EE-84CB-BA0FA8B13E50',
          openId: null,
          userId: '40669E98-830A-11EA-9338-0242C0A84606',
          account: 'admin',
          loginAccount: 'admin',
          userName: '管理员',
          tenantCode: 'RCSIT',
          userType: 'Employee',
          authorityPolicy: 'GlobalAdmin',
          locale: 'zh_CN',
          loginStatus: 'success',
          env: 'PROD',
          redirectUrl: null,
        },
      };
      if (account === 'admin' && password === 'jiyu123456') {
        result.success = true;
      } else {
        result.success = false;
        result.message = '账号或密码错误';
      }
      const { success, data, message: msg } = result || {};
      if (success) {
        yield put({
          type: 'menu/updateState',
          payload: {
            loginVisible: false,
          },
        });
        yield put({
          type: 'processUser',
          payload: {
            userInfo: data,
          },
        });
        yield take('processUser/@@end');
        /** 更新菜单相关状态 */
        yield put({
          type: 'menu/updateState',
          payload: {
            visibleTabData: [],
            moreTabData: [],
            activedMenu: null,
          },
        });
        router.replace('/');
      } else {
        notification.error({
          message: '登录失败',
          description: msg,
        });
      }
      return result;
    },
    *updatePwd({ payload }, { call }) {
      const result = yield call(updatePwd, payload);
      const { success, message: msg } = result || {};
      if (success) {
        message.success(msg);
      } else {
        message.error(msg);
      }

      return result;
    },
    *quickLogin({ payload }, { put, take }) {
      const result = yield userLogin({ ...payload, locale: adaptLocale(getCurrentLocale()) });
      const { success, data, message: msg } = result || {};
      const { loginStatus } = data || {};
      if (success && loginStatus === 'success') {
        yield put({
          type: 'processUser',
          payload: {
            userInfo: data,
          },
        });
        yield take('processUser/@@end');
      } else {
        notification.error({
          message: '请求错误',
          description: msg,
        });
      }

      return result;
    },
    *userLogout(_, { put }) {
      router.replace('/user/login');
      // yield userLogout();
      clearUserInfo();
      yield put({
        type: 'updateState',
        payload: {
          userInfo: null,
        },
      });
      /** 更新菜单相关状态 */
      yield put({
        type: 'menu/updateState',
        payload: {
          visibleTabData: [],
          moreTabData: [],
          activedMenu: null,
        },
      });
    },
    *redirectLogin(_, { put }) {
      router.replace('/user/login');
      /** 更新菜单相关状态 */
      yield put({
        type: 'menu/updateState',
        payload: {
          visibleTabData: [],
          moreTabData: [],
          activedMenu: null,
        },
      });
    },
    *getVerifyCode({ payload }, { call, put }) {
      const result = yield call(getVerifyCode, payload.reqId);
      const { success, data, message: msg } = result || {};
      if (success) {
        yield put({
          type: 'updateState',
          payload: {
            verifyCode: data,
          },
        });
      } else {
        message.error(msg);
      }
      return result;
    },
    *sendVerifyCode({ payload }, { call }) {
      const result = yield call(sendVerifyCode, payload);
      const { success, message: msg } = result || {};
      if (success) {
        message.success(msg);
        // TODO:
        // yield put({
        //   type: 'updateState',
        //   payload: {
        //     verifyCode: data,
        //   },
        // });
      } else {
        message.error(msg);
      }
      return result;
    },
    *checkExisted({ payload }, { call }) {
      const result = yield call(checkExisted, payload);
      const { success, message: msg } = result || {};
      if (success) {
        // TODO:
        // yield put({
        //   type: 'updateState',
        //   payload: {
        //     verifyCode: data,
        //   },
        // });
      } else {
        message.error(msg);
      }
      return result;
    },
    *findpwd({ payload }, { call }) {
      const result = yield call(findpwd, payload);
      const { success, message: msg } = result || {};
      if (success) {
        // TODO:
        // yield put({
        //   type: 'updateState',
        //   payload: {
        //     verifyCode: data,
        //   },
        // });
      } else {
        message.error(msg);
      }
      return result;
    },
  },

  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
